package com.cy.myblog.action.article;

import com.cy.myblog.action.BaseAction;
import com.cy.myblog.model.Tarticle;
import com.cy.myblog.model.Tclassify;
import com.cy.myblog.model.Tuser;
import com.cy.myblog.pageModel.Article;
import com.cy.myblog.pageModel.Json;
import com.cy.myblog.service.ArticleServiceI;
import com.cy.myblog.service.ClassifyServiceI;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/7/9.
 */
@Controller("articleAction")
@Scope("prototype")
public class ArticleAction extends BaseAction implements ModelDriven<Article>{

    private Article article = new Article();
    private ArticleServiceI articleService;
    private ClassifyServiceI classifyService;
    private File file;
    private String fileFileName;
    private String fileContentType;
    private Json json = null;

    public void validateAdd(){
        if(StringUtils.isBlank(article.getTitle()) || article.getTitle().length() == 0){
            this.addFieldError("title","标题不能为空");
        }

        if(StringUtils.isBlank(article.getContent())){
            this.addFieldError("container","内容不能为空");
        }
    }

    public String add(){
        json = new Json();
        StringBuffer fileName = new StringBuffer();

        Tuser user = (Tuser)session.get("loginUser");
        if(user == null){
            return "login";
        }

        Tarticle dbArticle = new Tarticle();
        dbArticle.setTitle(article.getTitle());
        dbArticle.setOverview(article.getOverview());
        dbArticle.setContent(article.getContent());
        dbArticle.setReleasetime(article.getReleasetime());
        dbArticle.setTclassify(classifyService.getById(article.getClassifyid()));
        dbArticle.setTuser(user);

        if(article.getReleasetime().getTime() < new Date().getTime()){
            dbArticle.setState(article.getState());
        }else{
            dbArticle.setState(0);
        }

        //文件上传
        if(fileFileName != null) {
            String rootPath = ServletActionContext.getServletContext().getRealPath("/upload");
             fileName = fileName.append(new Date().getTime()).append(fileFileName.substring(fileFileName.indexOf(".")));

            File rootFile = new File(rootPath);
            try {
                if (!rootFile.exists())
                    rootFile.mkdir();

                InputStream is = new FileInputStream(file);
                OutputStream os = new FileOutputStream(new File(rootFile, fileName.toString()));
                byte[] buffer = new byte[1024];
                int length = 0;

                while ((length = is.read(buffer)) != -1) {
                    os.write(buffer);
                }

                os.close();
                is.close();
            } catch (IOException e) {
                json.setMsg("上传文件出错了!");
                json.setRedirectPage("/jsp/backend/article/edit_article.jsp");
                return "message";
            }
        }
        json.setMsg("发布成功");
        json.setRedirectPage("/jsp/backend/article/edit_article.jsp");
        dbArticle.setFilename(StringUtils.isNotBlank(fileName) ? fileName.toString() : "");
        articleService.save(dbArticle);
        return "message";
    }

    public String loadClassify(){
        List<Tclassify> datas = classifyService.findAll();
        for(Tclassify data : datas)
            article.getClassifys().put(data.getId()+"",data.getClassifyname());
        return "tojson";
    }

    public void insertClassify(){
        json = new Json();
        if(StringUtils.isNotEmpty(article.getClassifyname())){
            Tclassify classify = new Tclassify();
            Map<String,String> data = new HashMap<String,String>();
            try {
                classify.setClassifyname(article.getClassifyname());
                classify.setState(1);
                classifyService.save(classify);
                String id = classifyService.getByName(classify.getClassifyname()).getId() + "";
                data.put("id",id);
                data.put("name",classify.getClassifyname());
                json.setObj(data);
                json.setSuccess(true);
                writeJson(json);
            } catch (Exception e) {
                json.setMsg("数据异常,请重新输入");
                json.setSuccess(false);
                writeJson(json);
            }
        }else{
            json.setMsg("分类名称不能为空!");
            json.setSuccess(false);
            writeJson(json);
        }
    }

    @Override
    public Article getModel() {
        return article;
    }

    public void setArticle(Article article) {
        this.article = article;
    }

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public String getFileFileName() {
        return fileFileName;
    }

    public void setFileFileName(String fileFileName) {
        this.fileFileName = fileFileName;
    }

    public String getFileContentType() {
        return fileContentType;
    }

    public void setFileContentType(String fileContentType) {
        this.fileContentType = fileContentType;
    }

    public Json getJson() {
        return json;
    }

    public void setJson(Json json) {
        this.json = json;
    }

    @Resource(name="articleService")
    public void setArticleService(ArticleServiceI articleService) {
        this.articleService = articleService;
    }

    @Resource(name="classifySerivce")
    public void setClassifyService(ClassifyServiceI classifyService) {
        this.classifyService = classifyService;
    }

}